from pymysql import connect, cursors

DEFAULT_SETTING = {
  'host': '127.0.0.1',
  'port': 3306,
  'database': 'su_ning',
  'user': 'root',
  'password': '123456',
}

def dbConnect(options):
 return connect(
    host = options['host'],
    port = options['port'],
    database = options['database'],
    user = options['user'],
    password = options['password'],
    cursorclass = cursors.DictCursor
  )

def dictSqlMap(tmp):
  keys = tmp.keys()
  value_str = ['%s' for x in range(len(keys))] 
  return ', '.join(keys), ', '.join(value_str), keys


class DB:
  def __init__(self):
    self.db = dbConnect(DEFAULT_SETTING)
    print('DB connect success !!!')
  
  # def getAll(self):
  #   sql = 'select * from shop where id=1'
    
  #   with self.db.cursor() as cur: 
  #     cur = self.db.cursor()
  #     cur.execute(sql)
  #     return cur.fetchone()
  
  def inset(self, table_name, data):
    _keys_str, _values_str, _keys = dictSqlMap(data)
    
    sql = 'insert into {} ({}) VALUES ({}) '.format(
      table_name,
      _keys_str,
      _values_str
    )

    _values = []
    for k in _keys:
      _values.append(data[k])

    with self.db.cursor() as cur:
      cur.execute(sql, tuple(_values))
    
    self.db.commit()
    print('save success !!!')


